﻿using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Text;
using System.IO;
using Microsoft.Phone.Shell;
using zhangkong;

namespace zhangkong
{
    public partial class Register : PhoneApplicationPage
    {

        private ApplicationBarIconButton verifyIconButton;
        private ApplicationBarIconButton okIconButton;



        private static bool IsRegister = false;

        //全局变量的申明
        public static string postback = "";
        public static string postdata = "";
        //
        public Register()
        {
            InitializeComponent();

            this.BackKeyPress += Register_BackKeyPress;
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Opacity = 0;

            verifyIconButton = new ApplicationBarIconButton(new Uri("/Toolkit.Content/Navigation-Right.png", UriKind.Relative));
            verifyIconButton.Text = "下一步";
            verifyIconButton.Click += verifyIconButton_Click;

            ApplicationBar.ForegroundColor = Colors.White;
            okIconButton = new ApplicationBarIconButton(new Uri("/Toolkit.Content/ApplicationBar.Check.png", UriKind.Relative));
            okIconButton.Text = "完成";
            okIconButton.Click += okIconButton_Click;
            ApplicationBar.Buttons.Add(verifyIconButton);

        }

        void okIconButton_Click(object sender, EventArgs e)
        {
            if (PasswordBox1.Password == "")
            {
                //MessageBox.Show("亲，密码不能为空哦！", "友情提示:", MessageBoxButton.OK);
                confirmTextBlock.Text = "亲，密码不能为空哦！";
                confirmStoryBoard.Begin();
                return;
            }
            else if (PasswordBox2.Password == "")
            {
                //MessageBox.Show("亲，密码不能为空哦！", "友情提示:", MessageBoxButton.OK);
                confirmTextBlock.Text = "亲，密码不能为空哦！";
                confirmStoryBoard.Begin();
                return;
            }
            //首先判读两次输入密码是否相同
            else if (PasswordBox1.Password != PasswordBox2.Password)
            {
                //MessageBox.Show("亲，两次密码不相同！");
                confirmTextBlock.Text = "亲，两次密码不相同！";
                confirmStoryBoard.Begin();
                PasswordBox1.Password = "";
                PasswordBox2.Password = "";
                return;
            }
            else
            {
                string uri = null;
                //postdata = "sno=201313030108&shenfen=130527199509292817&upwd=666666";
                //postdata = "sno=201213030215&shenfen=510104199401083778&upwd=123123123";//测试数据
                //postdata = "sno=123456789011&shenfen=123456789012345678&upwd=" + MD5_BASE64("12345678");
                if (IsRegister)
                {
                    uri = "http://202.115.137.129/zhangkong/register.php";
                    postdata = "sno=" + StudentID.Text + "&shenfen=" + ID.Text + "&upwd=" + MD5_BASE64(PasswordBox1.Password);
                }
                else
                {
                    uri = "http://202.115.137.129/zhangkong/changepassword.php";
                    postdata = "xuehao=" + StudentID.Text + "&upwd=" + MD5_BASE64(PasswordBox1.Password);
                }

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.BeginGetRequestStream(StreamCallback1, httpWebRequest);
                ProgressBar.Visibility = Visibility.Visible;

            }
        }

        void verifyIconButton_Click(object sender, EventArgs e)
        {
            postdata = "sno=" + StudentID.Text + "&shenfen=" + ID.Text;
            //verify ueser 

            string uri = "http://202.115.137.129/zhangkong/verifyusermessage.php";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.BeginGetRequestStream(StreamCallback, httpWebRequest);
            //
            ProgressBar.Visibility = Visibility.Visible;
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            IDictionary<string, string> queryString = NavigationContext.QueryString;
            if (queryString.ContainsKey("IsRegister"))
            {
                IsRegister = Convert.ToBoolean(queryString["IsRegister"]);
            }
            if (IsRegister)
            {
                RegisterTextBlock.Visibility = Visibility.Visible;
                FindTextBlock.Visibility = Visibility.Collapsed;
                //ConfitmButton.Content = "确认注册";
            }
            else
            {
                RegisterTextBlock.Visibility = Visibility.Collapsed;
                FindTextBlock.Visibility = Visibility.Visible;
                //ConfitmButton.Content = "确认修改";
            }


        }

        void Register_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (RegisterPivot.SelectedIndex == 1)
            {
                Step1Grid.Opacity = 0.8;
                Step2Grid.Opacity = 0.4;
                RegisterPivot.IsLocked = false;
                RegisterPivot.SelectedIndex = 0;
                RegisterPivot.IsLocked = true;


                ApplicationBar.Buttons.RemoveAt(0);
                ApplicationBar.Buttons.Add(verifyIconButton);

                e.Cancel = true;
            }
        }

        private void VerifyButton_Click(object sender, RoutedEventArgs e)
        {

            //此处建议显示一个ProgressBar
            //这里我只是做一个演示两秒钟后progressBar消失

            //这样的方法不可行……对于异步我表示完全无知，那这个效果就交给你了
            //下同
            //ProgressBar.Opacity = 1;
            //System.Threading.Thread.Sleep(4000);
            //ProgressBar.Opacity = 0;

            //此处要先验证学号和身份证信息
            //学生的学号x:Name为StudentID
            //身份证后四位为ID
            //

            postdata = "sno=" + StudentID.Text + "&shenfen=" + ID.Text;
            //verify ueser 

            string uri = "http://202.115.137.129/zhangkong/verifyusermessage.php";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.BeginGetRequestStream(StreamCallback, httpWebRequest);
            //
            ProgressBar.Visibility = Visibility.Visible;



        }

        //回调
        //下面进行回调函数
        ///////////////////
        private void StreamCallback(IAsyncResult result)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
            using (Stream stream = httpWebRequest.EndGetRequestStream(result))
            {
                byte[] entryBytes = Encoding.UTF8.GetBytes(postdata);
                stream.Write(entryBytes, 0, entryBytes.Length);
            }

            //这里就和上面GET方法获得回复回调一样，用 private void ResponseCallback(IAsyncResult result) 这个方法。
            httpWebRequest.BeginGetResponse(ResponseCallback, httpWebRequest);
        }
        //第二个回调函数
        private void ResponseCallback(IAsyncResult result)
        {
            Stream stream = null;

            try
            {
                //获取异步操作返回的的信息 
                HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                WebResponse webResponse = httpWebRequest.EndGetResponse(result);
                stream = webResponse.GetResponseStream();
                StreamReader sr = new StreamReader(stream, System.Text.UTF8Encoding.UTF8);
                //using (StreamReader sr = new StreamReader(stream))
                //{
                postback = sr.ReadToEnd();
                // }
            }
            catch
            {
                Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show("程序出现异常，请重试！");
                    confirmTextBlock.Text = "程序出现异常，请重试！";
                    confirmStoryBoard.Begin();
                });
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            if (postback == "1")
            {
                //因为HttpWebRequest是异步，不在UI线程上。所以要改变UI线程上的控件属性就要用Dispatcher.BeginInvoke()。  
                Dispatcher.BeginInvoke(() =>
                {
                    if (RegisterPivot.SelectedIndex == 0)
                    {
                        RegisterPivot.IsLocked = false;
                        RegisterPivot.SelectedIndex = 1;
                        Step1Grid.Opacity = 0.4;
                        Step2Grid.Opacity = 0.8;
                        RegisterPivot.IsLocked = true;
                    }
                    IsolatedStorageSettings.ApplicationSettings["StudentID"] = StudentID.Text;
                    IsolatedStorageSettings.ApplicationSettings["ID"] = ID.Text;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                    ProgressBar.Visibility = Visibility.Collapsed;
                    ApplicationBar.Buttons.RemoveAt(0);
                    ApplicationBar.Buttons.Add(okIconButton);
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show("请检查学号或身份证号是否正确!", "验证失败", MessageBoxButton.OK);
                    resetTextBlock.Text = "验证失败,请检查学号或身份证号是否正确!";
                    resetStoryBoard.Begin();
                    ProgressBar.Visibility = Visibility.Collapsed;
                });
            }


        }

        //回调结束



        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            if (PasswordBox1.Password == "")
            {
                //MessageBox.Show("亲，密码不能为空哦！", "友情提示:", MessageBoxButton.OK);
                confirmTextBlock.Text = "亲，密码不能为空哦！";
                confirmStoryBoard.Begin();
                return;
            }
            else if (PasswordBox2.Password == "")
            {
                //MessageBox.Show("亲，密码不能为空哦！", "友情提示:", MessageBoxButton.OK);
                confirmTextBlock.Text = "亲，密码不能为空哦！";
                confirmStoryBoard.Begin();
                return;
            }
            //首先判读两次输入密码是否相同
            else if (PasswordBox1.Password != PasswordBox2.Password)
            {
                //MessageBox.Show("亲，两次密码不相同！");
                confirmTextBlock.Text = "亲，两次密码不相同！";
                confirmStoryBoard.Begin();
                PasswordBox1.Password = "";
                PasswordBox2.Password = "";
                return;
            }
            else
            {
                string uri = null;
                //postdata = "sno=201313030108&shenfen=130527199509292817&upwd=666666";
                //postdata = "sno=201213030215&shenfen=510104199401083778&upwd=123123123";//测试数据
                //postdata = "sno=123456789011&shenfen=123456789012345678&upwd=" + MD5_BASE64("12345678");
                if (IsRegister)
                {
                    uri = "http://202.115.137.129/zhangkong/register.php";
                    postdata = "sno=" + StudentID.Text + "&shenfen=" + ID.Text + "&upwd=" + MD5_BASE64(PasswordBox1.Password);
                }
                else
                {
                    uri = "http://202.115.137.129/zhangkong/changepassword.php";
                    postdata = "xuehao=" + StudentID.Text + "&upwd=" + MD5_BASE64(PasswordBox1.Password);
                }

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.BeginGetRequestStream(StreamCallback1, httpWebRequest);
                ProgressBar.Visibility = Visibility.Visible;

            }

        }

        ///////////////////
        private void StreamCallback1(IAsyncResult result)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
            using (Stream stream = httpWebRequest.EndGetRequestStream(result))
            {
                byte[] entryBytes = Encoding.UTF8.GetBytes(postdata);
                stream.Write(entryBytes, 0, entryBytes.Length);
            }

            //这里就和上面GET方法获得回复回调一样，用 private void ResponseCallback(IAsyncResult result) 这个方法。
            httpWebRequest.BeginGetResponse(ResponseCallback1, httpWebRequest);
        }
        //第二个回调函数
        private void ResponseCallback1(IAsyncResult result)
        {
            Stream stream = null;

            try
            {
                //获取异步操作返回的的信息 
                HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                WebResponse webResponse = httpWebRequest.EndGetResponse(result);
                stream = webResponse.GetResponseStream();
                using (StreamReader sr = new StreamReader(stream, System.Text.UTF8Encoding.UTF8))
                {
                    postback = sr.ReadToEnd();
                }
            }
            catch
            {

                Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show("程序出现异常，请重试！");
                    ProgressBar.Visibility = Visibility.Collapsed;
                });
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            //因为HttpWebRequest是异步，不在UI线程上。所以要改变UI线程上的控件属性就要用Dispatcher.BeginInvoke()。  
            Dispatcher.BeginInvoke(() =>
            {
                if (postback == "失败")
                {
                    //MessageBox.Show("该账号已被注册，若忘记密码，请点忘记密码进行修改！");
                    confirmTextBlock.Text = "该账号已被注册，若忘记密码，请点忘记密码进行修改！";
                    confirmStoryBoard1.Begin();
                }
                else if (postback == "成功")//只有成功才会保存密码
                {
                    IsolatedStorageSettings.ApplicationSettings["Password"] = PasswordBox1.Password;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                    //MessageBox.Show("注册成功！");
                    confirmTextBlock.Text = "注册成功！";
                    confirmStoryBoard1.Begin();
                }
                else if (postback == "1")
                {
                    //MessageBox.Show("密码修改成功");
                    IsolatedStorageSettings.ApplicationSettings["Password"] = PasswordBox1.Password;
                    confirmTextBlock.Text = "密码修改成功";
                    confirmStoryBoard1.Begin();
                }
                else if (postback == "0")
                {
                    //MessageBox.Show("密码修改失败");
                    confirmTextBlock.Text = "密码修改失败";
                    confirmStoryBoard1.Begin();
                }
                else
                {
                    //MessageBox.Show("服务器异常，请等待一段时间再试");
                    confirmTextBlock.Text = "服务器异常，请等待一段时间再试";
                    confirmStoryBoard1.Begin();
                }

                ProgressBar.Visibility = Visibility.Collapsed;
                //NavigationService.GoBack();
            });



        }

        //回调结束







        private void StudentID_GotFocus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Opacity = 1;

            if (StudentID.Text == "")
            {
                studentID.Text = "";
            }
        }

        private void StudentID_LostFocus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Opacity = 0;
            if (StudentID.Text == "")
            {
                studentID.Text = "学号";
            }
        }

        private void ID_GotFocus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Opacity = 1;
            if (ID.Text == "")
            {
                id.Text = "";
            }
        }

        private void ID_LostFocus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Opacity = 0;
            if (ID.Text == "")
            {
                id.Text = "身份证号";
            }
        }
        //密码加密函数
        public static string MD5_BASE64(string data)
        {
            string password;
            password = MD5.GetMd5String(data).ToUpper();
            byte[] bytes = Encoding.UTF8.GetBytes(password);
            password = Convert.ToBase64String(bytes);
            return password;
        }

        private void NavigationTo(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        //下面为类尾

        private void PasswordBox1_OnGotFocus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Opacity = 1;
        }

        private void PasswordBox1_OnLostFocus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Opacity = 0;
        }
    }
}